"use client"

import { useState, useEffect, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { useRouter } from "next/navigation"
import {
  CalendarDays,
  BookOpen,
  CheckCircle,
  X,
  Send,
  User,
  Heart,
  BookMarked,
  Gem,
  Apple,
  Settings,
  Bell,
  LogOut,
  Award,
  Star,
  Calendar,
  BarChart3,
  FileText,
  Lock,
} from "lucide-react"
import {UserInfo} from "@/components/userinfo";
import useAppStore from "@/store/app.store";
import TodayQuote from "@/app/my/todayQuote";

export default function Home() {
  const router = useRouter()
  const [dailyTasks, setDailyTasks] = useState([
    {
      id: 1,
      title: "《般若波罗蜜多心经》校勘-初校语义对齐",
      type: "语义统一",
      difficulty: "中级难度",
      progress: 50,
      remainingTime: "0个月5天05小时",
      deadline: "03-31 23:59",
      estimatedDays: 30,
      characterCount: 5000 + Math.floor(Math.random() * 3000),
      estimatedMinutes: function () {
        return Math.ceil(this.characterCount / 100)
      },
    },
    {
      id: 2,
      title: "《般若波罗蜜多心经》校勘-初校语义对齐-词组",
      type: "原始对齐",
      difficulty: "中级难度",
      progress: 80,
      remainingTime: "1个月14天19小时",
      deadline: "05-10 23:59",
      estimatedDays: 30,
      characterCount: 5000 + Math.floor(Math.random() * 3000),
      estimatedMinutes: function () {
        return Math.ceil(this.characterCount / 100)
      },
    },
    {
      id: 3,
      title: "《般若波罗蜜多心经》校勘-二校精细校对",
      type: "字符完标",
      difficulty: "高级难度",
      progress: 30,
      remainingTime: "0个月22天05小时",
      deadline: "04-17 23:59",
      estimatedDays: 45,
      characterCount: 5000 + Math.floor(Math.random() * 3000),
      estimatedMinutes: function () {
        return Math.ceil(this.characterCount / 100)
      },
    },
  ])

  // 添加 URL 参数处理
  useEffect(() => {
    // 检查 URL 参数中是否有 tab
    const params = new URLSearchParams(window.location.search)
    const tabParam = params.get("tab")
    if (tabParam && ["精进", "随喜", "我执"].includes(tabParam)) {
      setActiveTab(tabParam)

      // 清除 URL 参数，但不刷新页面
      const newUrl = window.location.pathname
      window.history.replaceState({}, document.title, newUrl)
    }
  }, [])

  const [availableTasks, setAvailableTasks] = useState([
    {
      id: 4,
      title: "《金刚经》校勘-初校语义对齐",
      type: "语义统一",
      difficulty: "中级难度",
      estimatedDays: 30,
    },
    {
      id: 5,
      title: "《大般若经》校勘-初校语义对齐",
      type: "原始对齐",
      difficulty: "中级难度",
      estimatedDays: 30,
    },
    {
      id: 6,
      title: "《心经》校勘-初校语义对齐",
      type: "字符完标",
      difficulty: "中级难度",
      estimatedDays: 30,
    },
  ])

  const { activeTab, setActiveTab } = useAppStore((state) => state);
  const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false)
  const [taskToReview, setTaskToReview] = useState(null)
  const [isMobile, setIsMobile] = useState(false)
  const [isScrollingDown, setIsScrollingDown] = useState(false)
  const [lastScrollY, setLastScrollY] = useState(0)
  const [showFloatingAvatar, setShowFloatingAvatar] = useState(false)

  // Check if the device is mobile
  useEffect(() => {
    const checkIfMobile = () => {
      setIsMobile(window.innerWidth < 768)
    }

    checkIfMobile()
    window.addEventListener("resize", checkIfMobile)

    return () => {
      window.removeEventListener("resize", checkIfMobile)
    }
  }, [])

  // Handle scroll events
  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY

      // Determine scroll direction
      if (currentScrollY > lastScrollY) {
        setIsScrollingDown(true)
      } else {
        setIsScrollingDown(false)
      }

      // Show floating avatar when scrolled past the header
      if (currentScrollY > 100) {
        setShowFloatingAvatar(true)
      } else {
        setShowFloatingAvatar(false)
      }

      setLastScrollY(currentScrollY)
    }

    window.addEventListener("scroll", handleScroll, { passive: true })
    return () => window.removeEventListener("scroll", handleScroll)
  }, [lastScrollY])

  const refreshTasks = () => {
    // 模拟刷新任务的功能
    const newTasks = [
      {
        id: 7,
        title: "《楞严经》校勘-初校语义对齐",
        type: "语义统一",
        difficulty: "中级难度",
        estimatedDays: 35,
      },
      {
        id: 8,
        title: "《法华经》校勘-初校语义对齐",
        type: "原始对齐",
        difficulty: "中级难度",
        estimatedDays: 40,
      },
      {
        id: 9,
        title: "《维摩诘经》校勘-初校语义对齐",
        type: "字符完标",
        difficulty: "中级难度",
        estimatedDays: 25,
      },
    ]
    setAvailableTasks(newTasks)
  }

  const claimTask = (taskId) => {
    // 模拟领取任务的功能
    const task = availableTasks.find((t) => t.id === taskId)
    if (task) {
      const newTask = {
        ...task,
        progress: 0,
        remainingTime: "1个月0天0小时",
        deadline: "05-31 23:59",
      }

      setDailyTasks([...dailyTasks, newTask])
      setAvailableTasks(availableTasks.filter((t) => t.id !== taskId))
    }
  }

  const getTypeColor = (type) => {
    switch (type) {
      case "字符完标":
        return "bg-amber-brown/30 text-amber-brown-dark"
      case "原始对齐":
        return "bg-amber-brown/50 text-amber-brown-dark"
      case "语义统一":
        return "bg-amber-brown/70 text-amber-brown-dark"
      default:
        return "bg-amber-brown/30 text-amber-brown-dark"
    }
  }

  const getDifficultyColor = (difficulty) => {
    if (difficulty.includes("初级")) return "bg-amber-brown/20 text-amber-brown"
    if (difficulty.includes("中级")) return "bg-amber-brown/30 text-amber-brown"
    if (difficulty.includes("高级")) return "bg-amber-brown/40 text-amber-brown"
    return "bg-amber-brown/20 text-amber-brown"
  }

  const handleReviewConfirmation = (task) => {
    setTaskToReview(task)
    setIsConfirmDialogOpen(true)
  }

  const confirmReview = () => {
    if (taskToReview) {
      setDailyTasks(dailyTasks.filter((t) => t.id !== taskToReview.id))
      setIsConfirmDialogOpen(false)
      setTaskToReview(null)
    }
  }

  // 处理校对按钮点击
  const handleProofreadClick = (taskId) => {
    // 导航到校对页面
    router.push("/proofread")
  }

  // 在任务卡片中修改校对按钮的点击事件
  const renderTaskCards = () => {
    return dailyTasks.map((task) => (
      <div
        key={task.id}
        className="overflow-hidden bg-ancient-card/90 backdrop-blur-sm rounded-lg border border-amber-brown/30 shadow-ancient flex"
      >
        {/* 左侧任务类型标识 */}
        <div
          className={`writing-vertical py-3 md:py-4 px-1 md:px-2 flex items-center justify-center font-bold text-xs md:text-sm bg-amber-brown-dark text-white`}
        >
          {task.type}
        </div>

        <div className="p-3 md:p-4 flex-1">
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-2 sm:gap-0">
            <div className="flex-1">
              <h3 className="text-base md:text-lg font-bold line-clamp-2">{task.title}</h3>
            </div>
            <div className="self-end sm:self-start">
              <Button
                className="bg-amber-brown hover:bg-amber-brown-dark text-ancient-scroll text-sm h-8 md:h-9 px-3 md:px-4"
                aria-label="校对"
                onClick={() => handleProofreadClick(task.id)}
              >
                校对
              </Button>
            </div>
          </div>

          <div className="mt-3 md:mt-4">
            <Progress value={task.progress} className="h-1.5 md:h-2 bg-ancient-scroll/50" />
          </div>

          <div className="flex flex-wrap justify-between items-center mt-2 md:mt-3">
            <div className="text-xs md:text-sm text-ancient-text/70">
              {task.characterCount || 5000}/{(task.characterCount || 5000) + 2000}字数，预计需要
              {task.estimatedMinutes ? task.estimatedMinutes() : Math.ceil((task.characterCount || 5000) / 100)}
              分钟
            </div>
            <button
              className="text-xs md:text-sm text-ancient-text/60 hover:text-ancient-text/80 transition-colors flex items-center gap-1 py-1 px-2 rounded-md hover:bg-amber-brown/5"
              onClick={() => handleReviewConfirmation(task)}
              aria-label="发送审阅"
            >
              <Send className="h-3 w-3 md:h-3.5 md:w-3.5" />
              <span>发送审阅</span>
            </button>
          </div>
        </div>
      </div>
    ))
  }

  return (
    <div className="min-h-screen bg-ancient-scroll font-ancient text-ancient-text">
      <UserInfo active="精进" />

      <TodayQuote />

      <div className="container mx-auto p-3 md:p-6 pb-16 max-w-5xl">
        {/* 任务统计 */}
        <div className="mb-6 md:mb-8">
          <div className="p-3 sm:p-5 bg-ancient-card/90 backdrop-blur-sm rounded-lg border border-amber-brown/30 shadow-ancient">
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 md:gap-4 pt-1">
              <div className="flex items-center gap-3 bg-ancient-scroll/10 p-3 rounded-md">
                <BookOpen className="h-5 w-5 md:h-6 md:w-6 text-amber-brown flex-shrink-0" />
                <div>
                  <div className="hidden md:block text-xs sm:text-sm text-ancient-text/70">今日已完成</div>
                  <div className="text-sm sm:text-base md:text-lg font-bold">5,280/10,000字</div>
                </div>
              </div>
              <div className="flex items-center gap-3 bg-ancient-scroll/10 p-3 rounded-md">
                <CheckCircle className="h-5 w-5 md:h-6 md:w-6 text-amber-brown flex-shrink-0" />
                <div>
                  <div className="hidden md:block text-xs sm:text-sm text-ancient-text/70">小组项目进度</div>
                  <div className="text-sm sm:text-base md:text-lg font-bold">68%</div>
                </div>
              </div>
              <div className="flex items-center gap-3 bg-ancient-scroll/10 p-3 rounded-md">
                <CalendarDays className="h-5 w-5 md:h-6 md:w-6 text-amber-brown flex-shrink-0" />
                <div>
                  <div className="hidden md:block text-xs sm:text-sm text-ancient-text/70">累计总字数</div>
                  <div className="text-sm sm:text-base md:text-lg font-bold">1,245,600字</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 任务列表 */}
        <div className="mb-20 md:mb-8">
          <h3 className="text-base md:text-lg font-medium text-ancient-text mb-3 md:mb-4">我的任务</h3>

          <div className="space-y-3 md:space-y-4">
            {dailyTasks.length > 0 ? (
                renderTaskCards()
            ) : (
                <div className="text-center py-6 md:py-8 bg-ancient-card/50 rounded-lg border border-amber-brown/20">
                  <p className="text-ancient-text/70 mb-3 md:mb-4">您已完成所有任务</p>
                  <Button
                      className="bg-amber-brown hover:bg-amber-brown-dark text-ancient-scroll text-sm"
                      onClick={() => {
                        if (availableTasks.length > 0) {
                          claimTask(availableTasks[0].id)
                        } else {
                          refreshTasks()
                          setTimeout(() => {
                            if (availableTasks.length > 0) {
                              claimTask(availableTasks[0].id)
                            }
                          }, 500)
                        }
                      }}
                  >
                    继续领取
                  </Button>
                </div>
            )}
          </div>
        </div>
      </div>

      {/* Confirmation Dialog - Optimized for mobile and desktop */}
      {isConfirmDialogOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-ancient-card p-4 md:p-6 rounded-lg shadow-ancient max-w-md w-full mx-auto">
            <div className="flex justify-between items-center mb-3 md:mb-4">
              <h3 className="text-base md:text-lg font-medium text-amber-brown">确认发送审阅</h3>
              <button
                onClick={() => {
                  setIsConfirmDialogOpen(false)
                  setTaskToReview(null)
                }}
                className="text-ancient-text/60 hover:text-ancient-text/90 transition-colors"
                aria-label="关闭"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <p className="mb-5 md:mb-6 text-sm md:text-base">您确定要将此任务发送审阅吗？发送后将无法继续编辑。</p>
            <div className="flex justify-end gap-3">
              <Button
                variant="outline"
                className="border-amber-brown/30 text-amber-brown hover:bg-amber-brown/10 text-sm h-8 md:h-9"
                onClick={() => {
                  setIsConfirmDialogOpen(false)
                  setTaskToReview(null)
                }}
              >
                取消
              </Button>
              <Button
                className="bg-amber-brown hover:bg-amber-brown-dark text-ancient-scroll text-sm h-8 md:h-9"
                onClick={confirmReview}
              >
                确认发送
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
